package com.code.train.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.code.train.domain.TrainCarriage;
import com.code.train.domain.TrainSeat;
import com.code.train.domain.TrainSeatExample;
import com.code.train.enums.SeatColEnum;
import com.code.train.exception.BusinessException;
import com.code.train.exception.BusinessExceptionEnum;
import com.code.train.mapper.TrainSeatMapper;
import com.code.train.req.TrainSeatQueryReq;
import com.code.train.req.TrainSeatSaveReq;
import com.code.train.resp.PageResp;
import com.code.train.resp.TrainSeatQueryResp;
import com.code.train.service.TrainCarriageService;
import com.code.train.service.TrainSeatService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TrainSeatServiceImpl implements TrainSeatService {

    @Autowired
    private TrainSeatMapper trainSeatMapper;

    @Autowired
    private TrainCarriageService trainCarriageService;

    @Override
    public void save(TrainSeatSaveReq req) {
        DateTime now = DateTime.now();
        TrainSeat trainSeat = BeanUtil.copyProperties(req, TrainSeat.class);
        if (ObjectUtil.isNull(trainSeat.getId())) {
            trainSeat.setId(System.currentTimeMillis());
            trainSeat.setCreateTime(now);
            trainSeat.setUpdateTime(now);
            trainSeatMapper.insert(trainSeat);
        } else {
            trainSeat.setUpdateTime(now);
            trainSeatMapper.updateByPrimaryKey(trainSeat);
        }
    }

    @Override
    public PageResp<TrainSeatQueryResp> queryList(TrainSeatQueryReq req) {
        TrainSeatExample trainSeatExample = new TrainSeatExample();
        trainSeatExample.setOrderByClause("train_code asc,carriage_index asc,carriage_seat_index asc");
        TrainSeatExample.Criteria criteria = trainSeatExample.createCriteria();
        if (ObjectUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }

        log.info("查询页码：{}", req.getPage());
        log.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<TrainSeat> trainSeatList = trainSeatMapper.selectByExample(trainSeatExample);

        PageInfo<TrainSeat> pageInfo = new PageInfo<>(trainSeatList);
        log.info("总行数：{}", pageInfo.getTotal());
        log.info("总页数：{}", pageInfo.getPages());

        List<TrainSeatQueryResp> list = trainSeatList.stream()
                .map(trainSeat -> {
                    TrainSeatQueryResp resp = new TrainSeatQueryResp();
                    BeanUtils.copyProperties(trainSeat, resp);
                    return resp;
                })
                .collect(Collectors.toList());

        PageResp<TrainSeatQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    @Override
    public void delete(Long id) {
        trainSeatMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    @Override
    public void genTrainSeat(String trainCode) {
        DateTime now = DateTime.now();

        //查询当前车次的所有的车厢
        List<TrainCarriage> trainCarriages = trainCarriageService.selectByTrainCode(trainCode);
        if (CollUtil.isEmpty(trainCarriages)){
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CARRIAGE_NOT_EXIST);
        }

        //清空当前的车次的座位  这里要判断 生成的座位的车厢是否存在 还有
        TrainSeatExample trainSeatExample = new TrainSeatExample();
        TrainSeatExample.Criteria criteria = trainSeatExample.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode).andCarriageIndexIn(trainCarriages.stream().map(TrainCarriage::getIndex).collect(Collectors.toList()));
        trainSeatMapper.deleteByExample(trainSeatExample);

        //遍历车厢
        for (TrainCarriage trainCarriage : trainCarriages) {
            //获取车厢信息  行数  座位类型
            Integer rowCount = trainCarriage.getRowCount();
            String seatType = trainCarriage.getSeatType();
            int seatIndex = 1;
            //根据车厢类型 筛选出所有的列
            List<SeatColEnum> colsEnumList = SeatColEnum.getColsByType(seatType);
            //遍历行数
            for (int row = 1; row <= rowCount; row++) {
                //遍历列数
                for (SeatColEnum seatColEnum : colsEnumList) {

                    TrainSeat trainSeat = new TrainSeat();
                    trainSeat.setId(IdUtil.getSnowflake(1,1).nextId());
                    trainSeat.setTrainCode(trainCode);
                    trainSeat.setCarriageIndex(trainCarriage.getIndex());
                    trainSeat.setRow(StrUtil.fillBefore(String.valueOf(row), '0', 2));
                    trainSeat.setCol(seatColEnum.getCode());
                    trainSeat.setSeatType(seatColEnum.getType());
                    trainSeat.setCarriageSeatIndex(seatIndex++);
                    trainSeat.setCreateTime(now);
                    trainSeat.setUpdateTime(now);
                    trainSeatMapper.insert(trainSeat);
                }
            }

        }
    }

    @Override
    public List<TrainSeat> selectByTrainCode(String trainCode) {
        //清空当前的车次的座位
        TrainSeatExample trainSeatExample = new TrainSeatExample();
        trainSeatExample.setOrderByClause("'id' asc");
        TrainSeatExample.Criteria criteria = trainSeatExample.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode);

        //查询当前车次的所有的车厢
        return trainSeatMapper.selectByExample(trainSeatExample);
    }
}